package com.borimi.demo.gen;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.Collections;
import java.util.HashMap;

/**
 * Java 8 兼容版 MyBatis-Plus 代码生成器
 */
public class CodeGenerator2 {

    public static void main(String[] args) {

        // ✅ 修改为你自己的数据库配置
        String url = "jdbc:mysql://192.168.1.183:3306/blm_user_layer_activity?useUnicode=true&characterEncoding=utf8";
        String username = "pn";
        String password = "mSw3GZd7KmJ4nxJe";
    /*    String tables="days_template,platform_activity,platform_activity_user,platform_activity_user_epoch" +
                ",task_rule,task_rule_relation,task_template,user_days_template,user_task_record,user_window_record" +
                ",user_window_template,window_template";*/

        String tables="user_task_result";
        String[] tablesArray = tables.split(",");

        for (String s : tablesArray) {
            String ss =StringUtils.underlineToCamel(s);
            String sTable= ss.substring(0,1).toUpperCase()+ss.substring(1);
            // ✅ 代码输出目录
            String projectPath = System.getProperty("user.dir")+"\\";
            //String projectPath = "D:\\blmProject\\blm-web-api\\blm-modules\\blm-layer-activity\\";
            String parentPath = "com.blm.layer_activity";
            String outputDir = projectPath + "src\\main\\java\\";
            System.out.println(outputDir);
            FastAutoGenerator.create(url, username, password)
                    .globalConfig(builder -> {
                        builder.author("lzj")
                                .outputDir(outputDir)
                                .commentDate("yyyy-MM-dd")

                                .disableOpenDir();
                    })
                    .packageConfig(builder -> {
                        builder.parent(parentPath) // 父包名
                                .entity("domain")
                                .service("service")
                                .serviceImpl("service.impl")
                                .mapper("mapper")
                                .xml("mapper.xml")
                                .controller("controller")
                                //.other("vo")

                                // ✅ 自定义输出路径，用于生成 VO、QueryVO
                                .pathInfo(Collections.singletonMap(
                                        OutputFile.xml, projectPath + "/src/main/resources/mapper"
                                ));
                    })
                    .strategyConfig(builder -> {
                        builder.addInclude(s) // ✅ 要生成的表名
                                //.addTablePrefix("t_", "sys_")   // 去掉表前缀
                                .entityBuilder().enableLombok();
                                //.enableTableFieldAnnotation(false);
                    })
                    .templateEngine(new FreemarkerTemplateEngine())
                    .templateConfig(builder -> builder
                            .service("")
                            .serviceImpl("")
                            .mapper("")
                            .xml("/templates/mapper.xml" )
                            .entity( "")
                    )
                    .injectionConfig(consumer -> {
                        HashMap<String, String> customFiles = new HashMap<>();
                        // 每个表生成独立的 VO 和 QueryVO
                        customFiles.put("../../service/" + sTable + "Service.java", "/templates/service.java.ftl");
                        customFiles.put("../../service/impl/" + sTable + "ServiceImpl.java", "/templates/serviceImpl.java.ftl");
                        customFiles.put("../../mapper/" + sTable + "Mapper.java", "/templates/mapper.java.ftl");
                        customFiles.put("../../domain/vo/" + sTable + "VO.java", "/templates/vo.java.ftl");
                        customFiles.put("../../domain/queryvo/" + sTable  + "QueryVO.java", "/templates/queryvo.java.ftl");
                        customFiles.put("../../domain/" + sTable  + ".java", "/templates/entity.java.ftl");


                        // ✅ 手动指定输出路径，确保不会被拼在 vo 下
             /*           consumer.beforeOutputFile((tableInfo, objectMap) -> {
                            objectMap.put("serviceOutputDir", projectPath + "/src/main/java/com/blm/gen/service/");
                            objectMap.put("serviceImplOutputDir", projectPath + "/src/main/java/com/blm/gen/service/impl/");
                            objectMap.put("voOutputDir", projectPath + "/src/main/java/com/blm/gen/vo/");
                            objectMap.put("queryVoOutputDir", projectPath + "/src/main/java/com/blm/gen/vo/query/");
                        });*/
                        consumer.customFile(customFiles);
                    })

                    .execute();
            }
       /* String[] split = tables.split(",");
        for (String table : split) {
            generateExtraFiles(projectPath,  table);
        }
*/
        // ✅ 自定义扩展部分（VO、QueryVO）
       // generateExtraFiles(projectPath, "UserSignInLog");
    }

    /**
     * 额外生成 VO / QueryVO 类（示例）
     */
    private static void generateExtraFiles(String projectPath, String entityName) {
        String voPath = projectPath + "/src/main/java/com/blm/gen/vo/" + entityName + "VO.java";
        String queryVoPath = projectPath + "/src/main/java/com/blm/gen/vo/query/" + entityName + "QueryVO.java";

        String voContent = "package com.blm.gen.vo;\n\n" +
                "import lombok.Data;\n\n" +
                "@Data\n" +
                "public class " + entityName + "VO {\n" +
                "    private Long id;\n" +
                "    private String userName;\n" +
                "    private String activityType;\n" +
                "}\n";

        String queryVoContent = "package com.blm.gen.vo.query;\n\n" +
                "import lombok.Data;\n\n" +
                "@Data\n" +
                "public class " + entityName + "QueryVO {\n" +
                "    private String userName;\n" +
                "    private String dateRange;\n" +
                "}\n";

        try {
            java.nio.file.Files.createDirectories(java.nio.file.Paths.get(voPath).getParent());
            java.nio.file.Files.write(java.nio.file.Paths.get(voPath), voContent.getBytes());
            java.nio.file.Files.createDirectories(java.nio.file.Paths.get(queryVoPath).getParent());
            java.nio.file.Files.write(java.nio.file.Paths.get(queryVoPath), queryVoContent.getBytes());
            System.out.println("✅ 已生成 VO 和 QueryVO");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
